package com.jxust.vhrredis6000.handler;

import com.jxust.debate.util.CommonResult;
import org.bouncycastle.asn1.ocsp.ResponseData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;


@RestController
public class RedisHandler {
	
	@Autowired
	private StringRedisTemplate redisTemplate;


	@RequestMapping("/setRedisKeyAndValue")
	public CommonResult<String> setRedisKeyValueRemote(
			@RequestParam("key") String key, 
			@RequestParam("value") String value) {
		
		try {
			ValueOperations<String, String> operations = redisTemplate.opsForValue();
			
			operations.set(key, value);
			
			return CommonResult.success("插入成功");
		} catch (Exception e) {
			e.printStackTrace();
			
			return CommonResult.fail(e.getMessage());
		}
		
	}
	
	@RequestMapping("/setRedisKeyAndValueWithTimeOut")
	public CommonResult<String> setRedisKeyValueRemoteWithTimeout(
			@RequestParam("key") String key, 
			@RequestParam("value") String value,
			@RequestParam("time") long time,
			@RequestParam("timeUnit") TimeUnit timeUnit) {
		
		try {
			ValueOperations<String, String> operations = redisTemplate.opsForValue();
			
			operations.set(key, value, time, timeUnit);
			
			return  CommonResult.success();
		} catch (Exception e) {
			e.printStackTrace();
			
			return CommonResult.fail(e.getMessage());
		}
	}
	
	@RequestMapping("/getRedisValueByKey")
	public CommonResult<String>  getRedisStringValueByKeyRemote(@RequestParam("key") String key) {
		
		try {
			ValueOperations<String, String> operations = redisTemplate.opsForValue();
			
			String value = operations.get(key);
			if (value != null){
				return CommonResult.success("查找成功",value);
			}
			return CommonResult.fail("查找失败");
		} catch (Exception e) {
			e.printStackTrace();
			
			return CommonResult.fail(e.getMessage());
		}
		
	}

	@RequestMapping("/removeRedisKey")
	public CommonResult<String> removeRedisKeyRemote(@RequestParam("key") String key) {
		try {
			
			redisTemplate.delete(key);
			
			return CommonResult.success("删除成功");
			
		} catch (Exception e) {
			e.printStackTrace();
			
			return CommonResult.fail(e.getMessage());
		}
	}

}
